﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using DevComponents.DotNetBar;
using DevComponents.SuperGrid;

namespace IPR_TrainExamSys_TY.ScoreMrg
{
    public partial class FrmExamResultInput : Form
    {
        int iCurPaperTotalFenshu = 0;
        public FrmExamResultInput()
        {
            InitializeComponent();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
            openFileDialog1.Title = "选择要导入的模板";
            openFileDialog1.Multiselect = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                tbFileName.Text = openFileDialog1.FileName;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (tbFileName.Text == "") return;
            string msg = "";
            if (cmbPaperName.SelectedValue == null)
            {
                MessageBox.Show("试卷不存在,或者未添加,请先增加试卷！", "提示");
                return;
            }
            try
            {
                if (Import(tbFileName.Text, new DataTable(), "", ref msg, cmbPaperName.SelectedValue.ToString()))
                {
                    System.Windows.Forms.MessageBox.Show(msg, "导入成功");
                    tbFileName.Text = "";
                    btnSearch_Click(sender, e);
                }
                else System.Windows.Forms.MessageBox.Show(msg, "导入失败");
                progressBar1.Visible = false;
            }
            catch (Exception exc)
            {
                progressBar1.Visible = false;
                MessageBox.Show(exc.Message, "导入失败");
            }
        
        }
        #region Import()
        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="factPath">文件路径</param>
        /// <param name="dt">DataTable对象</param>
        /// <returns>bool</returns>
        protected bool Import(string factPath, DataTable dt, string fileName, ref string msg,string paperID)
        {
            string sMsg = "";
            if (Common.NPOIHelper.GetExcel(factPath, ref dt, fileName))
            { 
                #region 导入员工信息模板
                if (dt.Rows.Count > 0)
                {
                    try
                    {
                        progressBar1.Visible = true;
                        progressBar1.Maximum = dt.Rows.Count ;
                        progressBar1.Minimum = 0;
                        #region 导入子表

                        string sfirsthj = "";
                        string sXM = "";
                        string sss = "";
                        for (int i = 3; i < dt.Rows.Count-1; i++)
                        {
                            progressBar1.Value++;
                            Application.DoEvents();
                            if ((dt.Rows[i][2].ToString() == "") && (dt.Rows[i][9].ToString() == ""))
                            {
                                sMsg += "序号为：+" + dt.Rows[i][0].ToString() + "行数据格式有误,不能导入\r\n";
                                continue;
                            }
                            Model.pe_llksjg mllksjgAddRow = RowTollksjg(dt.Rows[i]);

                            string sWhere = " GWHGZSBH='" + mllksjgAddRow.GWHGZSBH + "' ";

                            Model.T_PublicEmployee mEmployee = new T_PublicEmployee().GetModel(sWhere);
                            if (mEmployee == null)
                            {
                                sMsg += mllksjgAddRow.xm + " 人员信息未维护 ,请先维护再导入！\r\n";
                                continue;
                            }

                            bool bExist = false;
                            sWhere = " GWHGZSBH='" + mllksjgAddRow.GWHGZSBH + "' and paperBh='"+paperID+"'";

                            mllksjgAddRow.paperBh = paperID;
                            mllksjgAddRow.gh = mEmployee.EmployeeId;
                            mllksjgAddRow.ksls = DateTime.Now.ToString("yyyyMMddHHmmssff");
                            mllksjgAddRow.pxkssj = dtppxkssj.Value.ToString("yyyy-MM-dd HH:mm:ss");
                            mllksjgAddRow.pxjssj = dtppxjssj.Value.ToString("yyyy-MM-dd HH:mm:ss");
                            Model.pe_llksjg mllksjgSel = new pe_llksjg().GetModel(sWhere);
                            if (mllksjgSel == null)
                            {
                                new pe_llksjg().Add(mllksjgAddRow);
                            }
                            else
                            {
                                mllksjgAddRow.id = mllksjgSel.id;
                                new pe_llksjg().Update(mllksjgAddRow);

                                sMsg += mllksjgAddRow.xm + " 导入重复,成绩被修改!\r\n";

                            }
                           
                        }
                        msg = "导入完成\r\n" + sMsg;
                        return true;
                        #endregion

                    }
                    catch (Exception exc)
                    {
                        msg = exc.Message;
                        return false;
                    }
                }
                else
                {
                    msg = "数据格式有误，请检查！";
                    return false;
                }
                #endregion
            }
            else
            {
                msg = "导入数据格式有误，请检查！";
                return false;
            }
        }

        private Model.pe_llksjg RowTollksjg(DataRow myRow)
        {
            Model.pe_llksjg mllksjg = new Model.pe_llksjg();
            mllksjg.xm = myRow[1].ToString();
            mllksjg.GWHGZSBH = myRow[2].ToString();
            mllksjg.kssj = myRow[5].ToString();
            mllksjg.ExamAddr = myRow[8].ToString();
            mllksjg.ksjg = myRow[9].ToString();
            return mllksjg;
        }
        #endregion

        private void btnSearch_Click(object sender, EventArgs e)
        {
            superGridControl1.PrimaryGrid.Rows.Clear();
            string sql = "select ksls,gh,xm,ksjg,kssj,a.paperBh,c.paperName,WorkShop,ClassGroup,Job,ExamAddr,a.GWHGZSBH," +
                " LocomotiveNo,Sex,Nation,Native,PoliticalStatus,NL,JB,pxkssj,pxjssj from pe_llksjg a "+
                " left join T_PublicEmployee b on a.GWHGZSBH=b.GWHGZSBH  and a.gh=b.EmployeeId " +
                " left join pe_paperMa c on a.paperBh=c.paperBh "+
                " where 1=1 ";
                if(cmbPaperName.SelectedValue!=null)
                    sql+=" and a.paperBh='"+cmbPaperName.SelectedValue.ToString()+"' ";
            if(tbEmployeeId.Text.Trim()!="")
                 sql +="and gh='"+tbEmployeeId.Text.Trim()+"' ";
            if (tbEmployeeName.Text.Trim() != "")
                sql += " and xm like '%" + tbEmployeeName.Text.Trim() + "%'";
            sql += " order by a.id ";
            try
            {
                DataSet ds = new T_Public().Query(sql);
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            superGridControl1.PrimaryGrid.DataSource = ds.Tables[0];
                        }
            }
            catch (Exception exc)
            {

            }
        }

        private void FrmExamResultInput_Load(object sender, EventArgs e)
        {
            superTabControl1.SelectedTabIndex = 0;
            getPaperName();
            getExamEmployee();
            dtppxkssj.Value = DateTime.Now.AddDays(-7);
        }

        private void getPaperName()
        {
            try
            {
                string sOrder = " id desc ";
                DataSet ds = new pe_paperMa().GetList(0,"",sOrder);
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            cmbPaperName.DataSource = ds.Tables[0];
                            cmbPaperName.DisplayMember = "paperName";
                            cmbPaperName.ValueMember = "paperBh";
                            //cmbPaperName.SelectedIndex = 0;
                        }
            }
            catch (Exception exc)
            {
            }
        }

        private void getExamEmployee()
        {
            try
            {
                string sorder = " EmployeeId asc ";
                DataSet ds = new T_PublicEmployee().GetList(0, "", sorder);
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                cmbExamEmployee.Items.Add(ds.Tables[0].Rows[i]["EmployeeId"].ToString() + "_" + ds.Tables[0].Rows[i]["EmployeeName"].ToString() );
                                cmbgwhgzsbh.Items.Add(ds.Tables[0].Rows[i]["EmployeeId"].ToString() + "_" + ds.Tables[0].Rows[i]["GWHGZSBH"].ToString());
                            }
                        }
            }
            catch (Exception exc)
            {
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPaperAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Model.pe_paperMa mpaperMa = new Model.pe_paperMa();
                int iPaperbh = new T_Public().GetMaxID("id", "pe_paperMa");
                mpaperMa.paperBh = "P"+iPaperbh.ToString();
                mpaperMa.paperName = cmbPaperName.Text.Trim();
                mpaperMa.createUser = BaseClass.CLoginInfo.LoginEmployee.EmployeeName;
                mpaperMa.createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                mpaperMa.csn = "P" + mpaperMa.paperBh;

                string sWhere=" paperName='"+cmbPaperName.Text.Trim()+"' ";
                bool bExist = false;
                DataSet ds = new pe_paperMa().GetList(sWhere);
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            bExist = true;
                        }
                if (!bExist)
                {
                    if (new pe_paperMa().Add(mpaperMa) > 0)
                    {
                        getPaperName();
                        MessageBox.Show("试卷添加成功！", "试卷添加成功");
                    }
                }
                else
                {
                    MessageBox.Show("试卷名称重复！", "试卷重复");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "提示");
            }
        }

        private void getPaperDe(string paperbh)
        {
            try
            {
                superGridControl2.PrimaryGrid.Rows.Clear();
                string sql = "  select paperBh,case when a.tix=0 then '判断题' else case when a.tix=1 then '选择题' else case when a.tix=2 then '填空题' else case when a.tix=3 then '简答题' else case when a.tix=4 then '综合题' end end end end end  as tix," +
                    " a.tikBH,tikFenZhi,ShiT,'' as ShiTi, case when RightAnswer='Y' then '对' else case when RightAnswer='N' then '错' else RightAnswer end end as RightAnswer,b.bFenzhi from pe_paperDe a " +
                    "  left join pe_Tik b on a.tikBH=b.bh " +
                    " where paperBh='" + paperbh+ "'";
                DataSet ds = new T_Public().Query(sql);
                if (ds != null)
                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            iCurPaperTotalFenshu = 0;
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                iCurPaperTotalFenshu += Convert.ToInt32(ds.Tables[0].Rows[i]["tikFenZhi"].ToString());
                                byte[] bShiT = (byte[])ds.Tables[0].Rows[i]["ShiT"];
                                string sShiT = Encoding.Default.GetString(bShiT);
                                ds.Tables[0].Rows[i]["ShiTi"] = sShiT;
                            }
                            superGridControl2.PrimaryGrid.Title.Text = cmbPaperName.Text + "  总题目数量：" + ds.Tables[0].Rows.Count.ToString() + "   总分数：" + iCurPaperTotalFenshu.ToString();

                            superGridControl2.PrimaryGrid.DataSource = ds.Tables[0];
                            lbToalRows.Text = ds.Tables[0].Rows.Count.ToString();

                            superGridControl2.PrimaryGrid.SetActiveRow(superGridControl2.PrimaryGrid.GetRowFromIndex(0));
                            superGridControl2.PrimaryGrid.SetSelectedRows(0, 1, true);
                            tbTotalFenshu.Text = "0";
                        }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "提示");
            }
        }
        private void superTabControl1_SelectedTabChanged(object sender, DevComponents.DotNetBar.SuperTabStripSelectedTabChangedEventArgs e)
        {
            if (superTabControl1.SelectedTabIndex == 0)
            {
                //btnSearch_Click(e, new EventArgs());
            }
            if (superTabControl1.SelectedTabIndex == 1)
            {
                if (cmbPaperName.SelectedValue == null)
                {
                    superTabControl1.SelectedTabIndex = 0;
                }
            }
        }


        private void superGridControl2_SelectionChanged(object sender, DevComponents.DotNetBar.SuperGrid.GridEventArgs e)
        {
            if (e.GridPanel.SelectedRows == null) return;
            try
            {
                tbShiti.Text = e.GridPanel.GetCell(e.GridPanel.ActiveRow.RowIndex,3).Value.ToString();
                tbRightAnswer.Text = e.GridPanel.GetCell(e.GridPanel.ActiveRow.RowIndex, 4).Value.ToString();
                tbFenZhi.Text = e.GridPanel.GetCell(e.GridPanel.ActiveRow.RowIndex, 5).Value.ToString();

                tbInputAnswer.Text = e.GridPanel.GetCell(e.GridPanel.ActiveRow.RowIndex, 6).Value == null ? "" : e.GridPanel.GetCell(e.GridPanel.ActiveRow.RowIndex, 6).Value.ToString();
                tbInputFenshu.Text = e.GridPanel.GetCell(e.GridPanel.ActiveRow.RowIndex, 7).Value == null ? "0" : e.GridPanel.GetCell(e.GridPanel.ActiveRow.RowIndex, 7).Value.ToString();


                lbCurRowIndex.Text = (e.GridPanel.ActiveRow.RowIndex + 1).ToString();


                chbRight.Checked = false;
                chbWrong.Checked = false;

            }
            catch (Exception ex)
            {
            }
        }

        private void btnSubrect_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt16(tbInputFenshu.Text.Trim()) <= 0) return;
            else
            {
                tbInputFenshu.Text = (Convert.ToInt16(tbInputFenshu.Text.Trim()) - 1).ToString();
            }
        }

        private void tbInputFenshu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && (!Char.IsControl(e.KeyChar))) return;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt16(tbInputFenshu.Text.Trim()) >= Convert.ToInt16(tbFenZhi.Text.Trim())) return;
            else
            {
                tbInputFenshu.Text = (Convert.ToInt16(tbInputFenshu.Text.Trim()) + 1).ToString();
            }
        }

        private void chbRight_CheckedChanged(object sender, EventArgs e)
        {
            if (chbRight.Checked)
            {
                chbWrong.Checked = false;
                tbInputAnswer.Text = tbRightAnswer.Text;
                tbInputFenshu.Text = tbFenZhi.Text;
                btnNext_Click(sender, e);
            }
        }

        private void chbWrong_CheckedChanged(object sender, EventArgs e)
        {
            if (chbWrong.Checked)
            {
                chbRight.Checked = false;
                tbInputAnswer.Text = "";
                tbInputFenshu.Text = "0";
                btnNext_Click(sender, e);
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                if (superGridControl2.PrimaryGrid.ActiveRow == null) return;
                int iActiveRowNo = 0;
                iActiveRowNo = superGridControl2.PrimaryGrid.ActiveRow.RowIndex;
                superGridControl2.PrimaryGrid.GetCell(iActiveRowNo, 6).Value = tbInputAnswer.Text.Trim();
                superGridControl2.PrimaryGrid.GetCell(iActiveRowNo, 7).Value = tbInputFenshu.Text.Trim();

                if ((iActiveRowNo + 1).ToString() == lbToalRows.Text)
                {
                    tbTotalFenshu.Text = getExamTotalFenshu().ToString();
                    MessageBox.Show("评卷完成，请点击 “完成评卷”按钮保存结果！", "提示");
                    return;
                }
                superGridControl2.PrimaryGrid.SetSelectedRows(iActiveRowNo,1,false);
                superGridControl2.PrimaryGrid.SetActiveRow(superGridControl2.PrimaryGrid.GetRowFromIndex(iActiveRowNo+1));
                superGridControl2.PrimaryGrid.SetSelectedRows(iActiveRowNo+1, 1, true);

                tbTotalFenshu.Text = getExamTotalFenshu().ToString();

            }
            catch (Exception exc)
            {
            }
        }

        private void chbIsTotalOnly_CheckedChanged(object sender, EventArgs e)
        {
            if (chbIsTotalOnly.Checked)
            {
                tbTotalFenshu.ReadOnly = false;
                tbTotalFenshu.SelectAll();
            }
            else
            {
                tbTotalFenshu.ReadOnly = true;
            }
        }

        private int getExamTotalFenshu()
        {
            int iTotalFenShu=0;
            for (int i = 0; i < superGridControl2.PrimaryGrid.Rows.Count; i++)
            {
                if(superGridControl2.PrimaryGrid.GetCell(i, 7).Value == null)continue;
                else if ( superGridControl2.PrimaryGrid.GetCell(i, 7).Value.ToString() != "")
                    iTotalFenShu += Convert.ToInt32(superGridControl2.PrimaryGrid.GetCell(i, 7).Value.ToString());
            }
            return iTotalFenShu;
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            if (cmbPaperName.SelectedValue == null)
            {
                MessageBox.Show("请选择试卷", "提示");
                return;
            }
            if(cmbExamEmployee.Text=="")
            {
                MessageBox.Show("请选择考试人员", "提示");
                return;
            }
            if (tbTotalFenshu.Text.Trim() == "0")
            {
                MessageBox.Show("请输入总成绩", "提示");
                return;
            }
            List< Model.pe_llksjg> modelksjgList=new List<Model.pe_llksjg>();
            List<Model.pe_llksjginfo> modelksjginfoList = new List<Model.pe_llksjginfo>();

            Model.pe_llksjg mksjg = new Model.pe_llksjg();
            Model.pe_llksjginfo mksjginfo = new Model.pe_llksjginfo();

            try
            {

                mksjg.gh = cmbExamEmployee.Text.Split('_')[0];
                mksjg.xm = cmbExamEmployee.Text.Split('_')[1];

                mksjg.GWHGZSBH = getGWHGZSBH(mksjg.gh);
                mksjg.kssj = dtpkssj.Value.ToString("yyyy-MM-dd HH:mm:ss");
                mksjg.ExamAddr = tbExamAddr.Text.Trim();
                mksjg.paperBh = cmbPaperName.SelectedValue.ToString();
                mksjg.ksjg = tbTotalFenshu.Text.Trim();
                mksjg.ksls = DateTime.Now.ToString("yyyyMMddHHmmssff");
                mksjg.ExamBh = Convert.ToInt32(mksjg.ksls.Substring(mksjg.ksls.Length - 4));
                mksjg.csn = mksjg.ksls;
                mksjg.pxkssj = dtppxkssj1.Value.ToString("yyyy-MM-dd HH:mm:ss");
                mksjg.pxjssj = dtppxjssj1.Value.ToString("yyyy-MM-dd HH:mm:ss");
                modelksjgList.Add(mksjg);

                for (int i = 0; i < superGridControl2.PrimaryGrid.Rows.Count; i++)
                {
                    mksjginfo = new Model.pe_llksjginfo();
                    mksjginfo.ksls = mksjg.ksls;
                    mksjginfo.TiX = getTix(superGridControl2.PrimaryGrid.GetCell(i, 1).Value.ToString());
                    mksjginfo.stbh = Convert.ToInt32(superGridControl2.PrimaryGrid.GetCell(i, 2).Value.ToString());
                    mksjginfo.RightAnswer = superGridControl2.PrimaryGrid.GetCell(i, 4).Value == null ? "" : superGridControl2.PrimaryGrid.GetCell(i, 4).Value.ToString();
                    mksjginfo.ksAnswer = superGridControl2.PrimaryGrid.GetCell(i, 6).Value == null ? "" : superGridControl2.PrimaryGrid.GetCell(i, 6).Value.ToString();
                    mksjginfo.fs = superGridControl2.PrimaryGrid.GetCell(i, 7).Value == null ? "0" : superGridControl2.PrimaryGrid.GetCell(i, 7).Value.ToString();
                    mksjginfo.csn = mksjg.ksls;
                    modelksjginfoList.Add(mksjginfo);
                }
                long lr= new pe_llksjg().AddToTableList(modelksjgList, modelksjginfoList);
                if (lr > 0)
                {
                    MessageBox.Show("评分完成！", "完成");
                }
                else
                {
                    MessageBox.Show("评分存档出错，请联系管理员！", "提示");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "存档错误");
            }
        }

        private string getTix(string tixing)
        {
            string stix = "0";
            switch (tixing)
            {
                // a.tix=0 then '' else case when a.tix=1 then '' else case when a.tix=2 then '' else case when a.tix=3 then '' else case when a.tix=4 then ''
                case "判断题":
                    stix = "0";
                    break;
                case "选择题":
                    stix = "1";
                    break;
                case "填空题":
                    stix = "2";
                    break;
                case "简答题":
                    stix = "3";
                    break;
                case "综合题":
                    stix = "4";
                    break; 
            }
            return stix;
        }

        private string getGWHGZSBH(string gh)
        {
            string sr = "";
            for (int i = 0; i < cmbgwhgzsbh.Items.Count; i++)
            {
                if (cmbgwhgzsbh.Items[i].ToString().Split('_')[0] == gh)
                {
                    sr = cmbgwhgzsbh.Items[i].ToString().Split('_')[1];
                    break;
                }
            }
            return sr;
        }
        private void tbTotalFenshu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && (!Char.IsControl(e.KeyChar))) return;
        }

        private void tbTotalFenshu_KeyUp(object sender, KeyEventArgs e)
        {
            if(superGridControl2.PrimaryGrid.Rows.Count>0)
            if (Convert.ToInt32(tbTotalFenshu.Text) > Convert.ToInt32(iCurPaperTotalFenshu))
            {
                tbTotalFenshu.Text = iCurPaperTotalFenshu.ToString();
            }
        }

        private void tbInputFenshu_KeyUp(object sender, KeyEventArgs e)
        {
            if (Convert.ToInt32(tbInputFenshu.Text) > Convert.ToInt32(tbFenZhi.Text))
            {
                tbInputFenshu.Text = tbFenZhi.Text;
            }
        }

        private void cmbPaperName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPaperName.SelectedValue == null) return;
            btnSearch_Click(sender, e);
            getPaperDe(cmbPaperName.SelectedValue.ToString());
        }

        private void cmbExamEmployee_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPaperName.SelectedValue == null) return;
            if (cmbExamEmployee.Text.Trim() =="") return;
            string swhere = " gh='"+cmbExamEmployee.Text.Trim().Split('_')[0]+"' and paperBh='"+cmbPaperName.SelectedValue.ToString()+"'";
            Model.pe_llksjg mksjg= new pe_llksjg().GetModel(swhere);
            if (mksjg != null)
            {
                tbTotalFenshu.Text = mksjg.ksjg.ToString();
            }
            else tbTotalFenshu.Text = "0";
        }
    }
}
